<template>
  <div class="wallet dashboard-head">
    <NavBar />
    <div>
      <div class="head item">
        <div class="container">
          <div class="photo photo-level">
            <img :src="me.sysUser.avatar">
            <span :class="[`level`,`level_${me.sysUser.authType}`]"></span>
          </div>
          <div v-if="me.sysUser.authType==='0'||!me.sysUser.authType" class="name">
            <h1 class="ftz24">{{me.sysUser.userAccount}}</h1>
          </div>
          <div v-if="me.sysUser.authType === '1'||me.sysUser.authType === '2'||me.sysUser.authType === '3'" class="name">
            <div>
              <span class="ftz24">{{me.sysUser.authName}}</span>
              <i>我的主页</i>
            </div>
            <div>
              <span>关注 {{me.focusNum}}</span>
              <span>｜</span>
              <span>粉丝 {{me.fansNum}}</span>
            </div>
          </div>
          <div class="fr info">
            <ul>
              <li>
                <span class="ftz16">{{me.viewpointNum}}篇</span>
                <p>观点</p>
              </li>
              <li>
                <span class="ftz16">{{me.planNum}}篇</span>
                <p>计划</p>
              </li>
              <li>
                <span class="ftz16">{{me.answerNum}}次</span>
                <p>回答</p>
              </li>
              <li>
                <span class="ftz16">{{me.subscriptionNum}}次</span>
                <p>订阅量</p>
              </li>
              <li>
                <span class="ftz16">{{me.incomeAll}}中亿币</span>
                <p>收益</p>
                <!-- userId:{{me.sysUser.userId}} -->
              </li>
            </ul>
          </div>
        </div>
      </div>

      <div class="container-user">
        <div class="user-account item">
          <span>账户余额：{{walletData.income}}中亿币</span>
          <button class="recharge" @click="$router.push('/recharge')">充值</button>
          <button class="fr sign" @click="$router.push('/checkIn')">签到</button>
        </div>
        <div class="con w82 item fr">
          <div class="item-h">
            <span class="ftz16">我的钱包</span>
            <i class="fr">支付宝账号：{{walletData.accountNo}}</i>
          </div>
          <div class="con-c">
            <div class="con-c-t">
              <div class="cash" v-if="!loading">
                <div id="cash_num" v-if="showEye">
                  <div class="cash-num clearfix">
                    <span class="pull-left">
                      <span class="block color-gray">可用中亿币</span>
                      <span class="ftz30 color-red cur-money">{{walletData.income}}</span>
                    </span>
                    <span class="color-gray pull-left equal">=</span>
                    <span class="pull-left">
                      <span class="block color-gray">可提现金额（元）</span>
                      <span class="ftz30 color-red cur-money">{{parseInt(walletData.income*10)/100}}</span>
                    </span>
                    <button @click="withdrawalEvent()">立即提现</button>
                    <!-- <button class="recharge" @click="$router.push('/recharge')">充值</button> -->
                  </div>
                  <div class="cash-bot">
                    <dl>
                      <dt>总金额（中亿币）</dt>
                      <dt>{{walletData.incomeAll}}</dt>
                    </dl>
                    <dl>
                      <dt>冻结中亿币</dt>
                      <dt>{{walletData.freezeAll}}</dt>
                    </dl>
                    <dl>
                      <dt>累计提现（元）</dt>
                      <dt>{{walletData.withdrawalAll}}</dt>
                    </dl>
                    <dl>
                      <dt>支出中亿币</dt>
                      <dt>{{walletData.expendAll}}</dt>
                    </dl>
                  </div>
                </div>
              </div>
              <div class="cash-tip fr">
                <p>充值比例1:10</p>
                <p>提现比例10:1</p>
                <p>每次提现最小额度为￥100.00</p>
                <p>提现会在 3-5 个工作日内到账</p>
                <p>
                  <a href="javascript: void(0)" @click="$router.push('/declare')">收入结算与提现常见问题</a>
                </p>
              </div>
            </div>
            <div class="record">
              <div class="record-g" guid>
                <span @click="changeTab('income')" :class="{'on': curTab === 'income'}">收入记录</span>
                <span @click="changeTab('expend')" :class="{'on': curTab === 'expend'}">支出记录</span>
                <span @click="changeTab('withdrawal')" :class="{'on': curTab === 'withdrawal'}">提现记录</span>
                <span @click="changeTab('other')" :class="{'on': curTab === 'other'}">其他明细</span>
              </div>
              <!-- 收入记录 -->
              <div class="record-c" v-if="curTab === 'income'">
                <div class="record-tab">
                  <table>
                    <tr>
                      <th>栏目</th>
                      <th>事项</th>
                      <th>类型</th>
                      <th>时间</th>
                      <th>金额（中亿币）</th>
                      <th>实际收益（中亿币）</th>
                      <th>状态</th>
                    </tr>
                    <tr v-for="(item, index) in walletIncomeData.list" :key="index">
                      <td>{{item.columnName}}</td>
                      <td>{{item.businessDesc}}</td>
                      <td>{{item.sourceName}}</td>
                      <td>{{item.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</td>
                      <td>{{item.amount}}</td>
                      <td>{{item.actualIncome}}</td>
                      <td>{{item.status===0?'已出账':'已入账'}}</td>
                    </tr>
                  </table>
                </div>
                <button v-if="total>walletIncomeData.list.length" @click="loadMore('income')" class="record-more">点击加载更多...</button>
                <button v-if="total===walletIncomeData.list.length" class="record-more">数据已经全部加载</button>
              </div>
              <!-- 支出记录 -->
              <div class="record-c" v-if="curTab === 'expend'">
                <div class="record-tab">
                  <table>
                    <tr>
                      <th>栏目</th>
                      <th>事项</th>
                      <th>类型</th>
                      <th>支付方式</th>
                      <th>时间</th>
                      <th>金额（中亿币）</th>
                      <th>状态</th>
                    </tr>
                    <tr v-for="(item, index) in walletExpendData.list" :key="index">
                      <td>{{item.columnName}}</td>
                      <td>{{item.businessDesc}}</td>
                      <td>{{item.sourceName}}</td>
                      <td>{{item.payTypeName}}</td>
                      <td>{{item.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</td>
                      <td>{{item.amount}}</td>
                      <td>{{item.status===0?'已出账':'已失效'}}</td>
                    </tr>
                  </table>
                </div>
                <button v-if="total>walletExpendData.list.length" @click="loadMore('expend')" class="record-more">点击加载更多...</button>
                <button v-if="total===walletExpendData.list.length" class="record-more">数据已经全部加载</button>
              </div>
              <!-- 提现记录 -->
              <div class="record-c" v-if="curTab === 'withdrawal'">
                <div class="record-tab">
                  <table>
                    <tr>
                      <th>提现时间</th>
                      <th>提现方式</th>
                      <th>提现金额（元）</th>
                      <!-- <th>扣税（元）</th> -->
                      <th>实际到帐（元）</th>
                      <th>状态</th>
                    </tr>
                    <tr v-for="(item, index) in walletWithdrawalData.list" :key="index">
                      <td>{{item.withdrawalTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</td>
                      <td>{{item.payTypeName}}</td>
                      <td>{{item.withdrawalRMBAmount}}</td>
                      <!-- <td>{{item.deductionRevenue}}</td> -->
                      <td>{{item.withdrawalRealRMBAmount}}</td>
                      <td :title="item.remark">{{item.withdrawalStatusName}}</td>
                    </tr>
                  </table>
                </div>
                <button v-if="total>walletWithdrawalData.list.length" @click="loadMore('withdrawal')" class="record-more">点击加载更多...</button>
                <button v-if="total===walletWithdrawalData.list.length" class="record-more">数据已经全部加载</button>
              </div>
              <!-- 其他明细 -->
              <div class="record-c" v-if="curTab === 'other'">
                <div class="record-tab">
                  <table>
                    <tr>
                      <th>支付方式</th>
                      <th>类型</th>
                      <th>金额（中亿币）</th>
                      <!-- <th>扣税（元）</th> -->
                      <th>状态</th>
                      <th>时间</th>
                    </tr>
                    <tr v-for="(item, index) in otherData.list" :key="index">
                      <td>{{item.payTypeName}}</td>
                      <td>{{item.sourceName}}</td>
                      <td>{{item.amount}}</td>
                      <td>{{item.statusText}}</td>
                      <td>{{item.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</td>
                    </tr>
                  </table>
                </div>
                <button v-if="total>otherData.list.length" @click="loadMore('other')" class="record-more">点击加载更多...</button>
                <button v-if="total===otherData.list.length" class="record-more">数据已经全部加载</button>
              </div>
            </div>
          </div>
        </div>
        <div class="w15 item fl">
          <SideBar2 />
        </div>
      </div>
      <div class="draw" style="width: 0;height: 0;overflow: hidden;">
        <div id="wallet-layer">
          <div class='draw-c'>
            <div class='draw-c-t'>
              <span class='icon icon-zfb'></span>
              <span>{{me.sysUser.realName}}
                <p>{{walletData.accountNo}}</p>
              </span>
            </div>
            <div class='draw-c-i cash'><input type='text' v-model="withdrawalMoney" placeholder='请输入提现金额'>
              <a @click="withdrawalAll()" href='javascript:void(0)'>全部</a>
            </div>
            <div class='draw-c-i password'><input v-model="withdrawalPassword" type='password' placeholder='请输入登录密码，进行身份验证'></div>
            <div class='draw-tip'>温馨提示：单笔提现金额区间100~10000元</div>
            <button id='draw_btn' @click="applyWalletWithdrawal()" class='submit'>确认提现</button>
          </div>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>
<script>
import $ from 'jquery'
import NavBar from '@/components/nav-bar'
import SideBar2 from '@/components/side-bar2'
import Footer from '@/components/footer'
// import Laypage from '@/components/laypage'
import { mapState } from 'vuex'
import * as api from '@/service/api'
import CryptoJS from 'crypto-js'
export default {
  name: 'wallet',
  components: {
    NavBar,
    Footer,
    SideBar2
    // Laypage
  },
  data () {
    return {
      walletData: {},
      curTab: 'income',
      withdrawalMoney: '',
      withdrawalPassword: '',
      walletIncomeData: {
        list: []
      },
      walletExpendData: {
        list: []
      },
      walletWithdrawalData: {
        list: []
      },
      otherData: {
        list: []
      },
      showEye: true,
      pageNum: 1,
      pageSize: 10,
      total: null,
      loading: false
    }
  },
  created () {
    this.getWallet()
    this.getWalletIncome()
  },
  computed: {
    // 来源网址
    url () {
      return this.$route.query.url || ''
    },
    curRoute () {
      return this.$route.path
    },
    ...mapState({
      me: state => state.me
    })
  },
  mounted () {
  },
  methods: {
    withdrawalEvent () {
      let that = this
      that.withdrawalMoney = ''
      that.withdrawalPassword = ''
      if (!this.walletData.accountNo) {
        window.layer.open({
          title: '提示',
          btn: ['确定', '取消'],
          class: 'wallet',
          skin: 'report walletTip',
          type: 1,
          btnAlign: 'c',
          content: '去设置支付账号！',
          yes: function (index, layero) {
            if (window.layer) {
              window.layer.closeAll()
            }
            that.$router.push('/settingAuth?tab=zhifu')
          }
        })
        return false
      }
      window.layer.open({
        title: '申请提现',
        // btn: ['确定', '取消'],
        skin: 'addTag',
        type: 1,
        btnAlign: 'c',
        content: $('#wallet-layer'),
        yes: function (index, layero) {
          if (window.layer) {
            window.layer.close(index)
          }
        }
      })
    },
    changeTab (data) {
      this.curTab = data
      this.pageNum = 1
      switch (this.curTab) {
        case 'income':
          this.getWalletIncome()
          break
        case 'expend':
          this.getWalletExpend()
          break
        case 'withdrawal':
          this.getWalletWithdrawal()
          break
        case 'other':
          this.getWalletOther()
          break
      }
    },
    loadMore (data) {
      ++this.pageNum
      switch (this.curTab) {
        case 'income':
          this.getWalletIncome()
          break
        case 'expend':
          this.getWalletExpend()
          break
        case 'withdrawal':
          this.getWalletWithdrawal()
          break
        case 'other':
          this.getWalletOther()
          break
      }
    },
    withdrawalAll () {
      this.withdrawalMoney = parseInt(this.walletData.income * 10) / 100
    },
    async applyWalletWithdrawal () {
      if (!/^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(this.withdrawalMoney) || this.withdrawalMoney === 0) {
        window.layer.msg('请输入正确金额！')
        return false
      }
      if (this.withdrawalMoney > this.walletData.income) {
        window.layer.msg('提现金额超出！')
        return false
      }
      if (!this.withdrawalPassword.length) {
        window.layer.msg('请输入密码！')
        return false
      }
      // 申请提现
      let key = CryptoJS.enc.Base64.parse('MDEyMzQ1Njc4OUFCQ0RFRg==')
      let iv = CryptoJS.enc.Base64.parse('MDEyMzQ1Njc4OUFCQ0RFRg==')
      let encrypted = CryptoJS.AES.encrypt(this.withdrawalPassword, key, {
        iv: iv,
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC
      })
      let oldPassword = CryptoJS.enc.Utf8.parse(encrypted.ciphertext.toString())
      let base64Password = CryptoJS.enc.Base64.stringify(oldPassword)
      try {
        await api.applyWalletWithdrawal({
          withdrawalAmount: this.withdrawalMoney,
          password: base64Password
        })
        if (window.layer) {
          window.layer.closeAll()
        }
        window.layer.msg('申请成功！')
        this.getWallet()
        this.getWalletIncome()
      } catch (e) {
        console.log(e)
        // window.layer.closeAll()
      }
    },
    async getWalletIncome () {
      // 收入记录
      this.loading = true
      let res = await api.getWalletIncome({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      if (this.pageNum === 1) {
        this.walletIncomeData = res.data
      } else {
        this.walletIncomeData.list = this.walletIncomeData.list.concat(res.data.list)
      }
      this.total = res.data.total
      this.loading = false
    },
    async getWalletExpend () {
      // 支出记录
      let res = await api.getWalletExpend({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      if (this.pageNum === 1) {
        this.walletExpendData = res.data
      } else {
        this.walletExpendData.list = this.walletExpendData.list.concat(res.data.list)
      }
      this.total = res.data.total
    },
    async getWalletWithdrawal () {
      // 提现记录
      let res = await api.getWalletWithdrawal({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      if (this.pageNum === 1) {
        this.walletWithdrawalData = res.data
      } else {
        this.walletWithdrawalData.list = this.walletWithdrawalData.list.concat(res.data.list)
      }
      this.total = res.data.total
    },
    async getWalletOther () {
      // 其他明细
      let res = await api.getWalletOther({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      if (this.pageNum === 1) {
        this.otherData = res.data
      } else {
        this.otherData.list = this.otherData.list.concat(res.data.list)
      }
      this.total = res.data.total
    },
    async getWallet () {
      this.loading = true
      let res = await api.getWallet()
      this.walletData = res.data
      this.loading = false
    },
    fmoney (s, n) {
      /*
       * 参数说明：
       * s：要格式化的数字
       * n：保留几位小数 fmoney(12, 2) // 12.00
       * */
      n = n > 0 && n <= 20 ? n : 2
      s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + ''
      let l = s.split('.')[0].split('').reverse()
      let r = s.split('.')[1]
      let t = ''
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? ',' : '')
      }
      return t.split('').reverse().join('') + '.' + r
    },
    showMoney () {
      this.showEye = !this.showEye
    }
  }
}
</script>
<style lang="scss">
@import "../../style/res/user";
@import "../../style/res/counselorWallet";
.wallet .layui-layer {
  width: 400px !important;
  z-index: 99 !important;
}
.wallet {
  .equal {
    line-height: 53px;
    padding: 0 30px;
  }
  .cur-money {
    text-align: center;
    width: 100%;
    display: inline-block;
  }
}
.wallet .block {
  display: block;
}
.wallet .color-gray {
  color: #808080;
}
.walletTip .layui-layer-content {
  padding: 30px 60px !important;
}
.wallet .color-red {
  color: #fb4c4c;
}
.wallet {
  .user-account {
    height: 50px;
    margin-bottom: 20px;
    padding: 0 20px;
    line-height: 50px;
  }
  .user-account button {
    display: inline-block;
    vertical-align: middle;
    width: 62px;
    height: 28px;
    border-radius: 14px;
    margin: 9px 0;
  }
  .user-account .recharge {
    background-color: #fb4c4c;
    color: #fff;
    border: 1px solid #fb4c4c;
    margin-left: 8px;
  }
  .user-account .sign {
    border: 1px solid #fb4c4c;
    color: #fb4c4c;
  }
}
</style>
